<template>
  <div class="main h-[calc(100%-29px)]">
    <div class="w-full">
      <div v-if="queryShow" class="mb-[10px] w-full search-form">
        <el-form :inline="true" :model="queryForm.data" label-width="0px">
          <el-form-item>
            <el-input
              v-model="queryForm.data.blurry"
              clearable
              placeholder="请输入表名"
            />
          </el-form-item>
          <el-form-item class="ml-[10px]">
            <el-button type="primary" :icon="Search" @click="search"
              >搜索</el-button
            >
            <el-button :icon="RefreshLeft" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div class="w-full">
        <div class="w-full flex justify-between">
          <div class="buttons flex align-center">
            <el-button
              type="success"
              :icon="RefreshLeft"
              :disabled="!multipleSelection.length"
              @click="delSelect"
              >同步</el-button
            >
          </div>
          <div class="settings">
            <el-button-group class="ml-4">
              <el-button
                type="primary"
                :icon="Search"
                @click="queryShow = !queryShow"
              />
              <el-button type="primary" :icon="RefreshLeft" @click="getList" />
              <el-popover placement="bottom" :width="200" trigger="click">
                <template #reference>
                  <el-button type="primary" :icon="Grid" />
                </template>
                <el-checkbox
                  v-model="checkAll"
                  :indeterminate="isIndeterminate"
                  @change="handleCheckAllChange"
                  >全选</el-checkbox
                >
                <el-checkbox-group
                  v-model="checkedCities"
                  class="columns-show-group"
                  @change="handleCheckedCitiesChange"
                >
                  <el-checkbox
                    v-for="item in defaultColums.data"
                    :key="item.prop"
                    :label="item.prop"
                    >{{ item.label }}</el-checkbox
                  >
                </el-checkbox-group>
              </el-popover>
            </el-button-group>
          </div>
        </div>
        <div class="flex">
          <div class="role w-full">
            <div v-loading="loading" class="w-full mt-[10px]">
              <el-table
                ref="multipleTableRef"
                class="table"
                :data="tableData.data"
                style="width: 100%"
                @selection-change="handleSelectionChange"
              >
                <el-table-column
                  v-for="item in colums.data"
                  :key="item.prop"
                  :prop="item.prop"
                  :label="item.label"
                  :width="item.width"
                />
                <el-table-column fixed="right" label="操作" width="220">
                  <template #default="scope">
                    <el-button
                      type="primary"
                      size="small"
                      text
                      @click="preview(scope.row)"
                      >预览</el-button
                    >
                    <el-button
                      type="primary"
                      size="small"
                      text
                      @click="download(scope.row)"
                      >下载</el-button
                    >
                    <el-button
                      type="primary"
                      size="small"
                      text
                      @click="setting(scope.row)"
                      >配置</el-button
                    >
                    <el-button
                      type="primary"
                      size="small"
                      text
                      @click="toGen(scope.row)"
                      >生成</el-button
                    >
                  </template>
                </el-table-column>
              </el-table>
            </div>
            <div class="page w-full mt-[10px]">
              <el-pagination
                v-model:current-page="pageObj.data.currentPage"
                v-model:page-size="pageObj.data.pageSize"
                :page-sizes="[10, 20, 30, 40, 50, 100]"
                layout="total, sizes, prev, pager, next, jumper"
                :total="pageObj.data.total"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
              />
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { Delete, Grid, RefreshLeft, Search } from "@element-plus/icons-vue";
import { ElForm, ElNotification, ElTable } from "element-plus";
import { onMounted, reactive, ref } from "vue";
import { getCurrentLevel } from "@/api/system";
import {
  getGeneratorList,
  ResultGeneratorList,
  sync,
  generator
} from "@/api/generator";
import { useRouter } from "vue-router";
import { downloadFile, parseTime } from "@/utils";
const router = useRouter();
const queryShow = ref(true);
const queryForm = reactive({
  data: {
    blurry: undefined
  }
});
const resetQuery = () => {
  queryForm.data = {
    blurry: undefined
  };
};
const search = async () => {
  pageObj.data.currentPage = 1;
  let { content, totalElements } = await getData();
  pageObj.data.total = totalElements;
  tableData.data = content;
};
const getList = async () => {
  let { content, totalElements } = await getData();
  pageObj.data.total = totalElements;
  tableData.data = content;
};
const handleSizeChange = () => {
  search();
};
const handleCurrentChange = async () => {
  getList();
};
const getData = () => {
  loading.value = true;
  return new Promise<ResultGeneratorList>(async (resolve, reject) => {
    let data = await getGeneratorList({
      current: pageObj.data.currentPage,
      size: pageObj.data.pageSize,
      sort: "id,desc",
      name: queryForm.data.blurry ? queryForm.data.blurry : undefined
    });
    loading.value = false;
    resolve(data);
  });
};
const currentLevel = ref(3);
const init = async () => {
  const { level } = await getCurrentLevel();
  currentLevel.value = level;
};
init();
const tableData = reactive({
  data: []
});
const colums = reactive({
  data: [
    {
      label: "表名",
      prop: "tableName"
    },
    {
      label: "数据库引擎",
      prop: "engine"
    },
    {
      label: "字符编码集",
      prop: "coding"
    },
    {
      label: "备注",
      prop: "remark"
    },
    {
      label: "创建日期",
      prop: "createTime",
      width: "200px"
    }
  ]
});
const defaultColums = reactive({
  data: [
    {
      label: "表名",
      prop: "tableName"
    },
    {
      label: "数据库引擎",
      prop: "engine"
    },
    {
      label: "字符编码集",
      prop: "coding"
    },
    {
      label: "备注",
      prop: "remark"
    },
    {
      label: "创建日期",
      prop: "createTime",
      width: "200px"
    }
  ]
});
const loading = ref(false);
const multipleTableRef = ref<InstanceType<typeof ElTable>>();
const multipleSelection = ref([]);
const checkAll = ref(true);
const isIndeterminate = ref(false);
const checkedCities = ref([]);

const handleCheckAllChange = (val: boolean) => {
  checkedCities.value = val ? defaultColums.data.map(item => item.prop) : [];
  isIndeterminate.value = false;
  if (checkedCities.value.length) {
    colums.data = defaultColums.data;
  } else {
    colums.data = [];
  }
};
const pageObj = reactive({
  data: {
    currentPage: 1,
    pageSize: 10,
    total: 0
  }
});
const handleCheckedCitiesChange = (value: string[]) => {
  const checkedCount = value.length;
  checkAll.value = checkedCount === defaultColums.data.length;
  isIndeterminate.value =
    checkedCount > 0 && checkedCount < defaultColums.data.length;
  let cols = [];
  defaultColums.data.forEach(i => {
    if (value.indexOf(i.prop) > -1) {
      cols.push(i);
    }
  });
  colums.data = cols;
};
onMounted(() => {
  search();
  checkedCities.value = colums.data.map(item => item.prop);
});
const handleSelectionChange = val => {
  multipleSelection.value = val;
};
const delSelect = () => {
  const tables = [];
  multipleSelection.value.forEach(val => {
    tables.push(val.tableName);
  });
  loading.value = true;
  sync(tables)
    .then(() => {
      search();
      ElNotification({
        title: "系统提示",
        message: "同步成功",
        type: "success"
      });
      loading.value = false;
    })
    .then(() => {
      loading.value = false;
    });
};
const preview = row => {
  router.push("/generator/preview/" + row.tableName);
};
const download = row => {
  generator(row.tableName, 2).then(data => {
    // downloadFile(data, tableName, "zip");
    let a = document.createElement("a");
    const url = window.URL.createObjectURL(new Blob([data]));
    a.setAttribute("href", url);
    a.setAttribute(
      "download",
      parseTime(new Date()) + "-" + row.tableName + ".zip"
    );
    a.setAttribute("target", "_blank");
    let clickEvent = document.createEvent("MouseEvents");
    clickEvent.initEvent("click", true, true);
    a.dispatchEvent(clickEvent);
  });
};
const toGen = row => {
  generator(row.tableName, 0).then(data => {
    ElNotification({
      title: "系统提示",
      message: "生成成功",
      type: "success"
    });
  });
};
const setting = row => {
  router.push("/generator/config/" + row.tableName);
};
</script>

<style scoped lang="scss">
:deep(.el-dropdown-menu__item i) {
  margin: 0;
}

:deep(.el-button:focus-visible) {
  outline: none;
}

.main-content {
  margin: 24px 24px 0 !important;
}

.search-form {
  :deep(.el-form-item) {
    margin-right: 4px;
    margin-bottom: 0;
  }
}

.table {
  .el-button + .el-button {
    margin-left: 0 !important;
  }
}
</style>
